package com.culture.bootdemo.common.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 打印接口日志
 */
@Component
@Aspect
@Slf4j
public class WebLogAspect2 {

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    //    @Around(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    @Around(value = "execution(public * com.culture.bootdemo.controller..*.*(..))")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // String methodDesc = webLog.desc();
        String id = UUID.randomUUID().toString().trim().replaceAll("-", "");
        //日志追踪id
        MDC.put("uuid", id);

        Object[] args = joinPoint.getArgs();
        Stream<?> stream = ArrayUtils.isEmpty(args) ? Stream.empty() : Arrays.stream(args);
        //过滤掉参数，避免调用接口报错
        List<Object> logArgs = stream
                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(arg instanceof MultipartFile)))
                .collect(Collectors.toList());

        log.info("MethodName:{} uuid={} start RequestArgs -->:{}, ", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), id, JSON.toJSONString(logArgs));
        Object result = joinPoint.proceed();
        log.info("MethodName:{} uuid={} end ResponseArgs <--:{}, Time:{} ms", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), id, JSON.toJSONString(result), System.currentTimeMillis() - startTime.get());
        MDC.remove("uuid");
        startTime.remove();
        return result;


    }
}
